#!/usr/bin/python
# -*- coding: utf-8 -*-

#This file is part of pyLot library.
#
# pyLot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyLot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pyLot.  If not, see <http://www.gnu.org/licenses/>.

__author__ = u'Pierre Puiseux, Guillaume Baty'
__copyright__ = u"Copyright 2011-2012 (C) andheo, Université de Pau et des Pays de l'Adour"
__credits__ = [u'Pierre Puiseux', u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"


import sys
import optparse

from pyLot.core import (Path, ENCODING, LANG, unicode2_to_str,
                        unicode2_to_ASCIIstr, error, check_type)
from pyLot.interfaces import UiInterface
from _pylot.cli.pylotoptions import pyLotOptionParser, pyLotOptionGroup

def set_optparse_texts(action_text_list, field=u'help') :
  if field == u'help' :
    for action, text in action_text_list :
      if isinstance(action, optparse.Option) :
        action.help = text
      elif isinstance(action, (pyLotOptionGroup, optparse.OptionGroup)):
        action.set_description(text)
  elif field == u'title' :
    for action, text in action_text_list :
      if isinstance(action, (pyLotOptionGroup, optparse.OptionGroup)):
        action.set_title(text)
  elif field == u'metavar' :
    pass
  else :
    pass

class CliInterface(UiInterface):

  def __init__(self, handler=None, parser=None):
    UiInterface.__init__(self, handler)

    self.guiflag = False

    self._parser = None
    self._group = []

    self.version = 'UNKNOWN'
    self.description = 'UNKNOWN DESCRIPTION'
    self.usage = 'prog [opts]'

    self.initParser(parser)

  def _setTexts(self, action_text_list, field='help'):
    u"""
    available fields :
      - help : Group and Options
      - title : Group only
      - metavar : Options only
    """
    if field not in (u'help', u'title', u'metavar') :
      self.io.writeStderr(tr_(u'Unknown field "%(FIELD)s"') % dict(FIELD=field))
    set_optparse_texts(action_text_list, field)

#  def _fill(self, obj, action_list):
#    curlevel = self.handler.level
#    supported_groups = (pyLotOptionGroup, pyLotOptionParser,
#                        optparse.OptionGroup, optparse.OptionParser)
#    if not issubclass(type(group), supported_groups) :
#      classes = u', '.join([unicode(c) for c in supported_qwidgets])
#      raise ValueError, error(tr_(u'obj: %s required, got %s') % (classes, type(widget)))
#    for action in actions :
#      level = u'user'
#      if isinstance(action, tuple) :
#        if len(action) >= 2 :
#          level = action[1]
#          action = action[0]
#        else :
#          pass
#      if type(action) is unicode :
#        raise NotImplementedError
#      else :
#        print action, type(action)
#      elif issubclass(type(action), QAction) and good_level_2(curlevel, level) :
#        widget.addAction(action)
#      elif issubclass(type(action), QMenu) and good_level_2(curlevel, level) :
#        widget.addMenu(action)
#      elif issubclass(type(action), QWidget) and good_level_2(curlevel, level) :
#        widget.addWidget(action)

  def addGroup(self, group):
    if group not in self.group :
      self.group.append(group)
    return group

  def getGroup(self):
    return self._group

  def _setgroup(self, group):
    self._group = group

  def _setparser(self, parser):
    check_type(u'parser', parser, pyLotOptionParser)
    self._parser = parser

  parser = property(fget=lambda self:self._parser, fset=_setparser)

  group = property(fget=getGroup, fset=_setgroup)
  tr_ = property(fget=lambda self:self._handler.tr_)

  def translate(self, locale=None):
    if locale is None :
      locale = LANG

    # Install gettext translators (global and local to current plugin if available)
    self.handler.translate(locale)

    # translate submodules
    for module in self._children.values() :
      module.translate(locale)

    self._translate()

  def initParser(self, parser=None):
    if parser is None :
      self.parser = pyLotOptionParser(
        version=self.version,
        description=self.description,
        usage=self.usage,
        )
    else :
      self.parser = parser

    for module in self._children.values() :
      module.initParser(self.parser)

  def addPlugin(self, name, handler=None, plugin_id=None, aliases=[]):
    module = Plugin(name, self.guiflag)
    cli = module.cli_class(handler=handler, parser=self.parser)
    cli.createOptionGroups()

    if plugin_id is None :
      plugin_id = cli.handler.name

    if plugin_id in self._children :
      raise NameError, error(tr_(u'A plugin named "%s" yet exists, please change "plugin_id" argument') % plugin_id)
    else :
      self._children[plugin_id] = cli

    make_aliases(cli, self, aliases)

    return cli

  def autoAddGroups(self):
    u"""
    Generates groups concatenating child groups
    """
    self.createOptionGroups()

    for group in self.group :
      self.parser.add_option_group(group)

    for module in self._children.values() :
      for group in module.group :
        self.parser.add_option_group(group)

  def fillGroups(self):
    self._fillGroups()

  def createOptionGroups(self):
    self._createOptionGroups()
    return self.group

  def autoRunOption(self, option, method):
    try :
      opt_value = getattr(self.options, option.dest)
    except : # option not added to group or parser
      pass
    else :
      if opt_value :
        return method()

  def runOptions(self, options):
    self.options = options
    self._runOptions(options)

  def _runOptions(self, option):
    pass

  def _fillGroups(self):
    pass

  def _createOptions(self):
    pass

  def _createOptionGroups(self):
    pass

  def _createConnexions(self):
    pass

  def _translate(self):
    pass
